package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Users;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service(version = "1.0.0")
public class UsersApiImpl implements UsersApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveUsers(Users users) {
        if (users.getUserId() == null || users.getFriendId() == null)
            return null;
        // 检测是否该好友关系是否存在
        // 存在两种可能:
        //      1 -> 2
        //      2 -> 1
        Query queryTo = Query.query(Criteria.where("userId").is(users.getUserId()).and("friendId").is(users.getFriendId()));
        Users resultUsersTo = mongoTemplate.findOne(queryTo, Users.class);
        if (!(null == resultUsersTo))
            return null;
        Query queryFrom = Query.query(Criteria.where("friendId").is(users.getUserId()).and("userId").is(users.getFriendId()));
        Users resultUsersFrom = mongoTemplate.findOne(queryFrom, Users.class);
        if (!(null == resultUsersFrom))
            return null;
        //保存好友关系,两种情况 to/from 都存
        //to
        users.setDate(System.currentTimeMillis());
        users.setId(ObjectId.get());
        mongoTemplate.save(users);
        //from
        users.setId(ObjectId.get());
        Long userId = users.getUserId();
        users.setUserId(users.getFriendId());
        users.setFriendId(userId);
        mongoTemplate.save(users);
        //存储成功,返回users的Id
        return users.getId().toHexString();

    }

    //模糊查询分页在查询mysql数据库时完成,这里查询所有
    @Override
    public List<Users> queryAllUsersList(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return this.mongoTemplate.find(query, Users.class);
    }

    //非模糊查询,完成分页查询
    @Override
    public List<Users> queryUsersList(Long userId, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageable);
        return mongoTemplate.find(query,Users.class);
    }
}